/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projetluc;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author Lone_Wolf
 */
public class ModifierEntree extends JPanel {

    private Fenetre fenetre;
    private Entree mod_entree;
    private Entree old_entree;
    private Client client;
    private Employe employe;
    Font f = new Font("Times New Roman", Font.BOLD, 24);
    private GridBagLayout gbl;
    private GridBagConstraints gbc;
    private JLabel lblClient;
    private JLabel lblCode;
    private JLabel lblEmploye;
    private JLabel lblSalaire;
    private JLabel lblTemps;
    private JLabel lblTitre;
    private JLabel lblDate;
    private JLabel lblCout;
    private JLabel lblTache;
    private JTextField txtClient;
    private JTextField txtCode;
    private JTextField txtEmploye;
    private JTextField txtSalaire;
    private JTextField txtTemps;
    private JTextField txtDateJour;
    private JTextField txtDateMois;
    private JTextField txtDateAnnee;
    private Travail_Effectue liste_taches;
    private JComboBox combTache;
    private double temps;
    private double salaire;
    private double cout;
    private JButton btnModifier;
    private JButton btnAnnuler;
    private JButton btnSupprimer;
    private JPanel pnlResultats;
    private Search recherche;
    private int[] date;
    private boolean modifiable = false;

    public ModifierEntree(Fenetre fenetre, Entree entree) {
        this.fenetre = fenetre;
        this.mod_entree = entree;
        this.old_entree = entree;
        this.client = entree.getClient();
        this.employe = entree.getEmploye();
        this.date = entree.getDate();
        initComposantes();
        setModifiable(modifiable);
        buildInterface();
        verifierDate();

        fenetre.setTitle("Consulter une Entrée");
        //fenetre.setSize(500, 720);

        requestFirstFocus();
    }

    private void requestFirstFocus() {
        fenetre.addWindowFocusListener(new WindowAdapter() {

            public void windowGainedFocus(WindowEvent e) {
                txtCode.requestFocusInWindow();
            }
        });
        JFrame trick = new JFrame();
        trick.setVisible(true);
        trick.setVisible(false);
        fenetre.requestFocus();
    }

    private void initComposantes() {
        lblTitre = new JLabel("Consulter une Entrée");
        lblTitre.setFont(f);

        lblClient = new JLabel("Nom du Client : ");
        lblCode = new JLabel("Numéro du Client : ");
        lblEmploye = new JLabel("Nom de l'Employé : ");
        lblSalaire = new JLabel("Salaire de l'Employé : ");
        lblTemps = new JLabel("Temps : ");
        lblDate = new JLabel("Date du service (jj/mm/aaaa) : ");
        lblCout = new JLabel("Total : 0$");
        lblTache = new JLabel("Sélectionner la tâche effectuée : ");
        salaire = 0;
        temps = 0;
        combTache = new JComboBox(liste_taches.values());

        txtClient = new JTextField(client.getNom());
        txtCode = new JTextField(client.getCode());
        txtEmploye = new JTextField(employe.getNom());
        txtSalaire = new JTextField(mod_entree.getSalaire() + "");
        txtTemps = new JTextField(mod_entree.getTemps() + "");

        txtClient.addKeyListener(new GererBackSpace());
        txtCode.addKeyListener(new GererBackSpace());
        txtEmploye.addKeyListener(new GererBackSpace());
        txtSalaire.addKeyListener(new GererBackSpace());
        txtTemps.addKeyListener(new GererBackSpace());

        txtClient.addKeyListener(new GererFocus());
        txtCode.addKeyListener(new GererFocus());
        txtEmploye.addKeyListener(new GererFocus());
        txtSalaire.addKeyListener(new GererFocus());
        txtTemps.addKeyListener(new GererFocus());
        combTache.addKeyListener(new GererFocus());

        txtDateJour = new JTextField("" + mod_entree.getDay());
        txtDateMois = new JTextField("" + mod_entree.getMonth());
        txtDateAnnee = new JTextField("" + mod_entree.getYear());
        txtDateJour.addFocusListener(new GererFocusDates());
        txtDateMois.addFocusListener(new GererFocusDates());
        txtDateAnnee.addFocusListener(new GererFocusDates());
        txtDateAnnee.addKeyListener(new GererFocus());
        txtDateJour.addKeyListener(new GererFocus());
        txtDateMois.addKeyListener(new GererFocus());

        btnModifier = new JButton("Modifier");
        btnAnnuler = new JButton("Retour");
        btnSupprimer = new JButton("Supprimer");
        if (mod_entree.getFacturee()) {
            btnSupprimer.setEnabled(false);
        }
        btnModifier.addActionListener(new GererEvenements());
        btnAnnuler.addActionListener(new GererEvenements());
        btnSupprimer.addActionListener(new GererEvenements());

        pnlResultats = new JPanel();
        pnlResultats.setPreferredSize(new Dimension(470, 300));
    }

    private void setModifiable(boolean modifiable) {
        this.modifiable = modifiable;
        txtClient.setEditable(modifiable);
        txtCode.setEditable(modifiable);
        txtDateAnnee.setEditable(modifiable);
        txtDateJour.setEditable(modifiable);
        txtDateMois.setEditable(modifiable);
        txtEmploye.setEditable(modifiable);
        txtSalaire.setEditable(modifiable);
        txtTemps.setEditable(modifiable);
        combTache.setEnabled(modifiable);
    }

    private void buildInterface() {
        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();
        this.setLayout(gbl);
        gbc.fill = GridBagConstraints.BOTH;

        makeSeparator();
        makeSeparator();
        makeBorder();
        gbc.weightx = 0.1;
        //gbc.gridwidth = gbc.REMAINDER;
        gbl.setConstraints(lblTitre, gbc);
        this.add(lblTitre);
        gbc.gridwidth = gbc.REMAINDER;
        gbc.fill = GridBagConstraints.NONE;
        gbl.setConstraints(btnSupprimer, gbc);
        this.add(btnSupprimer);

        gbc.fill = GridBagConstraints.BOTH;
        makeSeparator();
        makeBorder();
        gbc.weightx = 0.1;                  //Bloc Code Client
        gbl.setConstraints(lblCode, gbc);
        this.add(lblCode);
        makeBorder();
        gbc.weightx = 1.0;
        gbc.gridwidth = 3;
        gbl.setConstraints(txtCode, gbc);
        this.add(txtCode);

        gbc.gridwidth = gbc.REMAINDER;      //bords + Separateur
        makeBorder();
        makeSeparator();
        makeBorder();

        gbc.weightx = 0.1;                  //Bloc Nom Client
        gbl.setConstraints(lblClient, gbc);
        this.add(lblClient);
        makeBorder();
        gbc.weightx = 1.0;
        gbc.gridwidth = 3;
        gbl.setConstraints(txtClient, gbc);
        this.add(txtClient);

        gbc.gridwidth = gbc.REMAINDER;      //bords + Separateur
        makeBorder();
        makeSeparator();
        makeBorder();

        gbc.weightx = 0.1;                  //Bloc Employe
        gbl.setConstraints(lblEmploye, gbc);
        this.add(lblEmploye);
        makeBorder();
        gbc.weightx = 1.0;
        gbc.gridwidth = 3;
        gbl.setConstraints(txtEmploye, gbc);
        this.add(txtEmploye);

        gbc.gridwidth = gbc.REMAINDER;      //bords + Separateur
        makeBorder();
        makeSeparator();
        makeBorder();

        gbc.weightx = 0.1;                  //Bloc Salaire Employe
        gbl.setConstraints(lblSalaire, gbc);
        this.add(lblSalaire);
        makeBorder();
        gbc.weightx = 1.0;
        gbc.gridwidth = 3;
        gbl.setConstraints(txtSalaire, gbc);
        this.add(txtSalaire);

        gbc.gridwidth = gbc.REMAINDER;      //bords + Separateur
        makeBorder();
        makeSeparator();
        makeBorder();

        gbc.weightx = 0.1;                  //Bloc Temps
        gbl.setConstraints(lblTemps, gbc);
        this.add(lblTemps);
        makeBorder();
        gbc.weightx = 1.0;
        gbc.gridwidth = 2;
        gbl.setConstraints(txtTemps, gbc);
        this.add(txtTemps);
        gbc.gridwidth = 1;
        gbl.setConstraints(lblCout, gbc);
        this.add(lblCout);

        gbc.gridwidth = gbc.REMAINDER;      //bords + Separateur
        makeBorder();
        makeSeparator();
        makeBorder();

        gbc.weightx = 0.1;                      //Tache
        gbl.setConstraints(lblTache, gbc);
        this.add(lblTache);
        makeBorder();
        gbc.weightx = 1.0;
        gbl.setConstraints(combTache, gbc);
        this.add(combTache);
        gbc.gridwidth = gbc.REMAINDER;

        gbc.gridwidth = gbc.REMAINDER;      //bords + Separateur
        makeBorder();
        makeSeparator();
        makeBorder();

        gbc.weightx = 0.1;                  //Bloc Date
        gbl.setConstraints(lblDate, gbc);
        this.add(lblDate);
        makeBorder();
        gbc.weightx = 0.3;
        gbc.gridwidth = 1;
        gbl.setConstraints(txtDateJour, gbc);
        this.add(txtDateJour);
        gbc.gridwidth = 1;
        gbl.setConstraints(txtDateMois, gbc);
        this.add(txtDateMois);
        gbc.gridwidth = 1;
        gbl.setConstraints(txtDateAnnee, gbc);
        this.add(txtDateAnnee);

        gbc.gridwidth = gbc.REMAINDER;      //bords
        makeBorder();
        makeSeparator();
        makeSeparator();

        makeBorder();                       //boutons
        gbc.weightx = 0.1;
        gbc.fill = gbc.NONE;
        gbl.setConstraints(btnAnnuler, gbc);
        gbl.setConstraints(btnModifier, gbc);
        this.add(btnAnnuler);
        makeBorder();
        gbl.setConstraints(btnModifier, gbc);
        this.add(btnModifier);
        makeBorder();
        makeSeparator();

        makeSeparator();                    //Search
        makeBorder();
        gbc.gridwidth = gbc.RELATIVE;
        gbl.setConstraints(pnlResultats, gbc);
        this.add(pnlResultats);
        gbc.gridwidth = gbc.REMAINDER;
        makeBorder();
    }

    private void makeSeparator() {
        JLabel sep = new JLabel(" ");
        gbc.gridwidth = gbc.REMAINDER;
        gbl.setConstraints(sep, gbc);
        this.add(sep);
        gbc.gridwidth = gbc.CENTER;
        gbc.weighty = 0;
    }

    private void makeBorder() {
        gbc.weightx = 0.1;
        JLabel sep = new JLabel(" ");
        gbl.setConstraints(sep, gbc);
        this.add(sep);
        gbc.gridwidth = gbc.CENTER;
    }

    private boolean validerDonnees() {
        boolean valide = false;

        if (!txtClient.getText().isEmpty()) {
            lblClient.setForeground(Color.darkGray);
            if (!txtEmploye.getText().isEmpty()) {
                lblEmploye.setForeground(Color.darkGray);
                if (!txtTemps.getText().isEmpty()) {
                    if (0 < Double.parseDouble(txtTemps.getText())) {
                        lblTemps.setForeground(Color.darkGray);
                    }
                    if (0 < Double.parseDouble(txtSalaire.getText())) {
                        lblSalaire.setForeground(Color.darkGray);

                        salaire = Double.parseDouble(txtSalaire.getText());
                        temps = Double.parseDouble(txtTemps.getText());
                        if (verifierDate()) {
                            lblDate.setForeground(Color.darkGray);
                            valide = true;
                        } else {
                            lblDate.setForeground(Color.red);
                            txtDateJour.requestFocusInWindow();
                        }
                    } else {
                        lblSalaire.setForeground(Color.red);
                        txtSalaire.requestFocusInWindow();
                    }
                } else {
                    lblTemps.setForeground(Color.red);
                    txtTemps.requestFocusInWindow();
                }
            } else {
                lblEmploye.setForeground(Color.red);
                txtEmploye.requestFocusInWindow();
            }
        } else {
            lblCode.setForeground(Color.red);
            txtCode.requestFocusInWindow();
        }

        return valide;
    }

    public boolean miseAJour(KeyEvent e) {
        pnlResultats.removeAll();
        pnlResultats.revalidate();
        pnlResultats.repaint();
        for (int i = 0; i < recherche.getArrResultats2().size() && i < 10; i++) {
            makeBorder();
            gbc.weightx = 0.1;
            gbc.fill = gbc.HORIZONTAL;
            gbc.gridwidth = gbc.RELATIVE;
            gbl.setConstraints(recherche.getArrResultats2().get(i), gbc);
            ((SearchResult) recherche.getArrResultats2().get(i)).addActionListener(new GererInstantSearch());
            pnlResultats.add(recherche.getArrResultats2().get(i));
            gbc.gridwidth = gbc.REMAINDER;
            makeBorder();
        }
        pnlResultats.revalidate();
        pnlResultats.repaint();

        boolean recommencer_recherche = false;

        if (e.getKeyCode() != e.VK_BACK_SPACE) {
            if (recherche.getArrResultats2().size() == 1) {
                ((SearchResult) recherche.getArrResultats2().get(0)).doClick();
            } else if (recherche.getArrResultats2().isEmpty()) {
                if (!((JTextField) e.getSource()).getText().isEmpty()) {
                    String temp = ((JTextField) e.getSource()).getText();
                    temp = temp.substring(0, temp.length() - 1);
                    ((JTextField) e.getSource()).setText(temp);
                    recommencer_recherche = true;
                }
            }
        } else {
            recommencer_recherche = true;
        }
        return recommencer_recherche;
    }

    public double calculerCout() {
        cout = salaire * temps;
        lblCout.setText("Total : " + cout + "$");
        return cout;
    }

    private boolean verifierDate() {
        int day = 0;
        int month = 0;
        int year = 0;
        boolean valide = true;

        try {
            year = Integer.parseInt(txtDateAnnee.getText());
        } catch (NumberFormatException nfe) {
            txtDateAnnee.setText("");
        }
        try {
            month = Integer.parseInt(txtDateMois.getText());
        } catch (NumberFormatException nfe) {
            txtDateMois.setText("");
        }
        try {
            day = Integer.parseInt(txtDateJour.getText());
        } catch (NumberFormatException nfe) {
            txtDateJour.setText("");
        }

        //valide = DateUtils.isValidDateStr(annee + "-" + mois + "-" + jour);
        valide = DateUtils.isValidDateInt(year, month, day);
        if (valide) {
            date[0] = year;
            date[1] = month;
            date[2] = day;
        }
        return (valide);
    }

    class GererFocusDates implements FocusListener {

        public void focusGained(FocusEvent e) {
        }

        public void focusLost(FocusEvent e) {
            if (e.getSource() == txtDateJour || e.getSource() == txtDateMois || e.getSource() == txtDateAnnee) {
                if (!txtDateAnnee.getText().isEmpty()) {
                    if (!txtDateMois.getText().isEmpty()) {
                        if (!txtDateJour.getText().isEmpty()) {
                            verifierDate();
                        }
                    }
                }
            }
        }
    }

    class GererEvenements implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == btnModifier) {
                if (modifiable == false) {
                    setModifiable(true);
                    btnModifier.setText("Appliquer les modifications");
                    txtCode.requestFocusInWindow();
                } else {
                    if (validerDonnees()) {
                        old_entree.setYear(date[0]);
                        old_entree.setMonth(date[1]);
                        old_entree.setDay(date[2]);
                        old_entree.setEmploye(employe);
                        old_entree.setClient(client);
                        old_entree.setTemps(temps);
                        old_entree.setSalaire(salaire);
                        old_entree.setTache((Travail_Effectue) combTache.getSelectedItem());

                        /*
                         * fenetre.arEntree.add(new Entree(date, employe,
                         * client, temps, salaire, (Travail_Effectue)
                         * combTache.getSelectedItem()));
                         * fenetre.arEntree.remove(old_entree);
                         */
                        try {
                            fenetre.sauvegarderBD();
                        } catch (IOException ex) {
                            Logger.getLogger(CreerNouvClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        btnAnnuler.doClick();
                    }
                }
            } else if (e.getSource() == btnAnnuler) {
                fenetre.afficherConsulterClient(client);
            } else if (e.getSource() == btnSupprimer) {
                int reponse = JOptionPane.showConfirmDialog(null, "Êtes-vous certain de vouloir supprimer cette entrée?", "Confirmation", JOptionPane.YES_NO_OPTION);
                if (reponse == 0) {
                    fenetre.arEntree.remove(old_entree);
                    try {
                        fenetre.sauvegarderBD();
                        fenetre.afficherConsulterClient(client);

                    } catch (IOException ex) {
                        Logger.getLogger(CreerNouvClient.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }

    class GererBackSpace implements KeyListener {

        public void keyTyped(KeyEvent e) {
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            if (e.getSource() == txtClient) {
                if (e.getKeyCode() == e.VK_BACK_SPACE) {
                    txtCode.setText("");
                }
                boolean[] params = new boolean[7];
                params[0] = true;
                recherche = new Search(fenetre, txtClient.getText(), params);
                if (miseAJour(e)) {
                    recherche = new Search(fenetre, txtClient.getText(), params);
                }
            } else if (e.getSource() == txtCode) {
                if (e.getKeyCode() == e.VK_BACK_SPACE) {
                    txtClient.setText("");
                }
                boolean[] params = new boolean[7];
                params[0] = true;
                recherche = new Search(fenetre, txtCode.getText(), params);
                if (miseAJour(e)) {
                    recherche = new Search(fenetre, txtCode.getText(), params);
                }
            } else if (e.getSource() == txtEmploye) {
                if (e.getKeyCode() == e.VK_BACK_SPACE) {
                    txtSalaire.setText("");
                }
                boolean[] params = new boolean[7];
                params[2] = true;
                recherche = new Search(fenetre, txtEmploye.getText(), params);
                if (miseAJour(e)) {
                    recherche = new Search(fenetre, txtEmploye.getText(), params);
                    calculerCout();
                }
            } else if (e.getSource() == txtTemps) {
                if (!txtTemps.getText().isEmpty()) {
                    temps = Double.parseDouble(txtTemps.getText());
                } else {
                    temps = 0;
                }
                calculerCout();
            } else if (e.getSource() == txtSalaire) {
                if (!txtSalaire.getText().isEmpty()) {
                    salaire = Double.parseDouble(txtSalaire.getText());
                } else {
                    salaire = 0;
                }
            }
            calculerCout();
        }
    }

    class GererInstantSearch implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            TypeDonnees type = ((SearchResult) e.getSource()).getType();
            switch (type) {
                case CLIENT:
                    client = ((SearchResult) e.getSource()).getClient();
                    txtClient.setText(client.getNom());
                    txtCode.setText(client.getCode());
                    break;
                case EMPLOYE:
                    employe = ((SearchResult) e.getSource()).getEmploye();
                    txtEmploye.setText(employe.getNom());
                    txtSalaire.setText("" + employe.getSalaire());
                    salaire = employe.getSalaire();
            }
        }
    }

    class GererFocus implements KeyListener {

        public void keyTyped(KeyEvent e) {
        }

        public void keyPressed(KeyEvent e) {
        }

        /**
         * permet de changer le focus d'un champ de texte (JTextField) à un
         * autre grâce à la touche "Entrée".
         *
         * @param e permet d'itentifier la source dans laquelle une touche a
         * étée relâchée.
         */
        public void keyReleased(KeyEvent e) {
            if (e.getSource() == txtClient) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    try {
                        ((JButton) pnlResultats.getComponent(0)).doClick();
                    } catch (Exception e2) {
                    }
                    pnlResultats.removeAll();
                    txtEmploye.requestFocusInWindow();
                }
            } else if (e.getSource() == txtCode) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    try {
                        ((JButton) pnlResultats.getComponent(0)).doClick();
                    } catch (Exception e2) {
                    }
                    pnlResultats.removeAll();
                    txtEmploye.requestFocusInWindow();
                }
            } else if (e.getSource() == txtEmploye) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    try {
                        ((JButton) pnlResultats.getComponent(0)).doClick();
                    } catch (Exception e2) {
                    }
                    pnlResultats.removeAll();
                    txtTemps.requestFocusInWindow();
                }
            } else if (e.getSource() == txtTemps) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    combTache.requestFocusInWindow();
                }
            } else if (e.getSource() == combTache) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    txtDateJour.requestFocusInWindow();
                }
            } else if (e.getSource() == txtDateJour) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    txtDateMois.requestFocusInWindow();
                }
            } else if (e.getSource() == txtDateMois) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    txtDateAnnee.requestFocusInWindow();
                }
            } else if (e.getSource() == txtDateAnnee) {
                if (e.getKeyCode() == e.VK_ENTER) {
                    btnModifier.doClick();
                }
            }
        }
    }
}
